<?php
//ini_set('display_errors', 1);
//error_reporting(E_ALL);

function ss( $key )
{
	return isset($_SESSION[$key])?$_SESSION[$key]:false;
}

function ss_set( $key , $value )
{
	return $_SESSION[$key] = $value;
}

function teacher_ss( $key )
{
	return isset($_SESSION['teacher'][$key])?$_SESSION['teacher'][$key]:false;
}

function teacher_ss_set( $key , $value )
{
	return $_SESSION['teacher'][$key] = $value;
}

function is_login()
{
	if( isset( $_COOKIE['PHPSESSID'] ) )
	{
		session_start();
		return teacher_ss('teacher_id') > 0;
	}
	
	return false;
}

function is_admin()
{
	return teacher_ss('level') > 5 ;
}

function is_xmk_trialor()
{
	return teacher_ss('level')==6;
}

function is_expert()
{
	return teacher_ss('level')==2;
}

function is_leader()
{
	return teacher_ss('level')==3;
}

function is_department_leader()
{
	return teacher_ss('level')==4;
}

function rjoin(  $sp , $str , $array )
{
	$ret = array();
	foreach( $array as $key => $value )
	{
		$ret[] = $str.trim($value , $str ).$str;
	}
	
	return join( $sp , $ret );
}

function has_saekv()
{
	if( defined('SAE_ACCESSKEY') && substr( SAE_ACCESSKEY , 0 , 4 ) == 'kapp' ) return false;
 	return in_array( 'SaeKV' , get_declared_classes() );
	//return false;
}

if( !has_saekv() ) @mkdir( AROOT. '__lr3_kv');

function kget( $key )
{
	if( has_saekv() )
	{
		$kv = new SaeKV();$kv->init();
		$value = $kv->get( $key );
		if(is_NULL($value) || $value == "")
			$value=temp_kget_out( $key );
		return $value;
	}
	else
	{
		$keyfile = AROOT. '__lr3_kv' . DS . 'kv-'.md5($key);
		return @unserialize( @file_get_contents($keyfile) );
	}
}

function kset( $key , $value , $backup = TRUE)
{
	if( has_saekv() )
	{
		$kv = new SaeKV();$kv->init();
		//写一份到__meta_setting表中
		if ($backup){
			if( temp_kset_into( $key , $value ) ) return $kv->set( $key , $value );
		}else{
			return $kv->set( $key , $value );
		}
	}
	else
	{
		$keyfile = AROOT. '__lr3_kv' . DS . 'kv-'.md5($key);
		return @file_put_contents($keyfile , serialize( $value )  );
	}
}

/**
*Validate an email address.
*Provide email address (raw input)
*Returns true if the email address has the email 
*address format and the domain exists.
*URL: http://developer.51cto.com/art/200810/92652_3.htm
*/
function validEmail($email)
{

   $isValid = true;
   $atIndex = strrpos($email, "@");

   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

//Encrypt and Decrypt

function encrypt($string,$key)
{
	$plain_text = trim($string);
	$iv = substr( md5($key),0,mcrypt_get_iv_size(MCRYPT_CAST_256,MCRYPT_MODE_CFB) );
	$c_t = mcrypt_cfb(MCRYPT_CAST_256,$key,$plain_text,MCRYPT_ENCRYPT,$iv);
	return trim(chop(base64_encode($c_t)));
}

function decrypt($string,$key)
{
	$string=trim(chop(base64_decode($string)));
	$iv = substr( md5($key),0,mcrypt_get_iv_size(MCRYPT_CAST_256,MCRYPT_MODE_CFB) );
	$c_t = mcrypt_cfb(MCRYPT_CAST_256,$key,$string,MCRYPT_DECRYPT,$iv);
	return trim(chop($c_t));
}

//Random String
function generate_rand_str($len)
{
	$c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	srand((double)microtime()*1000000);
	for($i=0;$i<$len;$i++)
	{
		$rand .=$c[rand()%strlen($c)];
	}
	return $rand;
}

function dohash($str1, $str2) {
	return hash('sha256', $str1 . $str2);
}

function send_mail( $email , $subject , $content )
{
	if( c('on_sae') )
	{
		require_once(AROOT . 'lib' .DS. 'apibus' .DS. 'apibus.class.php');
		$sc= apibus::init('sendcloud');
		$result = $sc->send_mail(
		  'postmaster@cqtbi.sendcloud.org' , //api_user, 需要登录SendCloud创建收信域名获取发送账号
		  'KP4Wnexu7vFnGFlq',  // api_key，需要登录SendCloud创建收信域名获取发送账号。
		  'postmaster@mail.cqtbi.esch.cn', // from， 发件人地址
		  '渝电大(工商职院)教务处项目管理科',  // fromname， 发件人称呼
		  $subject,   // subject，邮件主题
		  $email, //to， 收件人
		  $content	//html， html形式的邮件正文
		);
		return (($result->message)=="success")?0:$result->message;

		// $m = new SaeMail();
		// $m->clean();	
		// $m->quickSend( $email , $subject , $content , c('smtp_account') , c('smtp_password') , c('smtp_server') , c('smtp_port') );

		// $m->setOpt( array(
		// 		 'from' => '重庆工商职业学院质量工程信息系统 <'.c('smtp_account').'>',
		// 		 'to' => $email,
		// 		 'smtp_host' => c('smtp_server'),
		// 		 'smtp_port' => c('smtp_port'),
		// 		 'smtp_username' => c('smtp_account'),  
		// 		 'smtp_password' => c('smtp_password'),  
		// 		 'subject' => $subject,  
		// 		 'content' => $content, 
		// 		 'content_type' => "HTML"
		// ) ); 
		// $ret = $m->send();

		// return $m->errno();
	}else{
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
		curl_setopt($ch, CURLOPT_URL, 'https://sendcloud.sohu.com/webapi/mail.send.json');
    //不同于登录SendCloud站点的帐号，您需要登录后台创建发信子帐号，使用子帐号和密码才可以进行邮件的发送。
		curl_setopt($ch, CURLOPT_POSTFIELDS,
			array(
				'api_user' => 'postmaster@cqtbi.sendcloud.org',
				'api_key' => 'KP4Wnexu7vFnGFlq',
				'from' => 'postmaster@mail.cqtbi.esch.cn',
				'fromname' => '渝电大(工商职院)教务处项目管理科',
				'to' => $email,
				'subject' => $subject,
				'html' => $content
				));        
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		$result = curl_exec($ch);

		if($result === false) //请求失败
		{
			echo 'last error : ' . curl_error($ch);
		}

		curl_close($ch);

		return $result;
	}
}

function send_sms($mobile_phone,$content)
{
	//return true;
	if(c('on_sae')){
		require_once(AROOT . 'lib' .DS. 'apibus' .DS. 'apibus.class.php');
		define("SAE_ACCESSKEY", "3yoonzlyox");
		define("SAE_SECRETKEY", "3yikzz2zxk2kmkxyh5z3hkjhx50imklh3h50ilhh");
		//载入方法一
		$bechsms = apibus::init("bechsms");
		$akey="484";
		$skey="d813101120fb79a7216ade3a41d3c1aa88eec7ad";
		$code = $bechsms->sendmsg($akey,$skey,$mobile_phone,$content);
		$status=json_decode($code);
	}else{

		//利用Curl
		//set POST variables
/*		$url = 'http://sms.bechtech.cn/Api/send/data/json?accesskey=484&secretkey=d813101120fb79a7216ade3a41d3c1aa88eec7ad&mobile='.$mobile_phone.'&content='.urlencode($content);
		//open connection
		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);

		//execute post
		$code = curl_exec($ch);

		//close connection
		curl_close($ch);*/

		/*
		********************************************
		*
		*改用学校的短信接口
		*不会限制数量，非常好，加强验证
		*SOAP
		*
		**********************************************
		*/
		$wsdl = "http://61.186.170.114/sms/Service.asmx?wsdl";
		$client = new SoapClient($wsdl);

		$appID="3";
		$appToken="B656AFCCEF79BA6226E3EB6824C8B297";


		$strMd5=strtoupper(md5($appID.$appToken));

		//参数赋值
		$param = array('appId'=>$appID,'strMD5'=>$strMd5,'Mobiles'=>$mobile_phone, 'SmContent'=>$content.date('Y-m-d H:i:s',time()));

		//发送短信
		$code = $client->SendMs($param);
		return (($code->SendMsResult)=="短信发送成功")?1:0;

	}
	return $status;
}

function point_to_rank($point,$node_score)
{
	if($point==$GLOBALS['score_rank']['F']*$node_scrore*1000)
		return "F";
	else if(bccomp($point,$GLOBALS['score_rank']['A']*$node_score*1000,0)==0)
		return "A";

	else if(bccomp($point,$GLOBALS['score_rank']['B']*$node_score*1000,0)==0)
		return "B";
	else if(bccomp($point,$GLOBALS['score_rank']['C']*$node_score*1000,0)==0)
		return "C";
	else if(bccomp($point,$GLOBALS['score_rank']['D']*$node_score*1000,0)==0)
		return "D";
	else if(bccomp($point,$GLOBALS['score_rank']['E']*$node_score*1000,0)==0)
		return "E";
}

function html2pdf_word_wrap($str,$len=31)
{
	$arr=str_split_unicode($str, $len);
	foreach ($arr as $s) {
		$return_str .=$s;
	}
	return $return_str;
}

/**
 * 将unicode字符串按传入长度分割成数组
 * @param  string  $str 传入字符串
 * @param  integer $l   字符串长度
 * @return mixed      数组或false
 */

 function str_split_unicode($str, $l = 0) {
    if ($l > 0) {
        $ret = array();
        $len = mb_strlen($str, "UTF-8");
        for ($i = 0; $i < $len; $i += $l) {
            $ret[] = mb_substr($str, $i, $l, "UTF-8")."<br/>";
        }
        return $ret;
    }
    return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
 }



function file_pop_download($name)
{
							// send headers to browser
	header('Content-Description: File Transfer');
	if (headers_sent()) {
		$this->Error('Some data has already been output to browser, can\'t send PDF file');
	}
	header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
	header('Pragma: public');
	header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
	// force download dialog
	header('Content-Type: application/force-download');
	header('Content-Type: application/octet-stream', false);
	header('Content-Type: application/download', false);
	header('Content-Type: application/pdf', false);
	// use the Content-Disposition header to supply a recommended filename
	header('Content-Disposition: attachment; filename="'.basename($name).'";');
	header('Content-Transfer-Encoding: binary');
	header('Content-Length: '.filesize($name));
	// send document to the browser
	echo file_get_contents($name);
}

/** 
 * 人民币小写转大写 
 * 
 * @param string $number 数值 
 * @param string $int_unit 币种单位，默认"元"，有的需求可能为"圆" 
 * @param bool $is_round 是否对小数进行四舍五入 
 * @param bool $is_extra_zero 是否对整数部分以0结尾，小数存在的数字附加0,比如1960.30， 
 *             有的系统要求输出"壹仟玖佰陆拾元零叁角"，实际上"壹仟玖佰陆拾元叁角"也是对的 
 * @return string 
 */ 

function num2rmb($number = 0, $int_unit = '元', $is_round = TRUE, $is_extra_zero = FALSE) 
{ 
    // 将数字切分成两段 
    $parts = explode('.', $number, 2); 
    $int = isset($parts[0]) ? strval($parts[0]) : '0'; 
    $dec = isset($parts[1]) ? strval($parts[1]) : ''; 
 
    // 如果小数点后多于2位，不四舍五入就直接截，否则就处理 
    $dec_len = strlen($dec); 
    if (isset($parts[1]) && $dec_len > 2) 
    { 
        $dec = $is_round 
                ? substr(strrchr(strval(round(floatval("0.".$dec), 2)), '.'), 1) 
                : substr($parts[1], 0, 2); 
    } 
 
    // 当number为0.001时，小数点后的金额为0元 
    if(empty($int) && empty($dec)) 
    { 
        return '零'; 
    } 
 
    // 定义 
    $chs = array('0','壹','贰','叁','肆','伍','陆','柒','捌','玖'); 
    $uni = array('','拾','佰','仟'); 
    $dec_uni = array('角', '分'); 
    $exp = array('', '万'); 
    $res = ''; 
 
    // 整数部分从右向左找 
    for($i = strlen($int) - 1, $k = 0; $i >= 0; $k++) 
    { 
        $str = ''; 
        // 按照中文读写习惯，每4个字为一段进行转化，i一直在减 
        for($j = 0; $j < 4 && $i >= 0; $j++, $i--) 
        { 
            $u = $int{$i} > 0 ? $uni[$j] : ''; // 非0的数字后面添加单位 
            $str = $chs[$int{$i}] . $u . $str; 
        } 
        //echo $str."|".($k - 2)."<br>"; 
        $str = rtrim($str, '0');// 去掉末尾的0 
        $str = preg_replace("/0+/", "零", $str); // 替换多个连续的0 
        if(!isset($exp[$k])) 
        { 
            $exp[$k] = $exp[$k - 2] . '亿'; // 构建单位 
        } 
        $u2 = $str != '' ? $exp[$k] : ''; 
        $res = $str . $u2 . $res; 
    } 
 
    // 如果小数部分处理完之后是00，需要处理下 
    $dec = rtrim($dec, '0'); 
 
    // 小数部分从左向右找 
    if(!empty($dec)) 
    { 
        $res .= $int_unit; 
 
        // 是否要在整数部分以0结尾的数字后附加0，有的系统有这要求 
        if ($is_extra_zero) 
        { 
            if (substr($int, -1) === '0') 
            { 
                $res.= '零'; 
            } 
        } 
 
        for($i = 0, $cnt = strlen($dec); $i < $cnt; $i++) 
        { 
            $u = $dec{$i} > 0 ? $dec_uni[$i] : ''; // 非0的数字后面添加单位 
            $res .= $chs[$dec{$i}] . $u; 
        } 
        $res = rtrim($res, '0');// 去掉末尾的0 
        $res = preg_replace("/0+/", "零", $res); // 替换多个连续的0 
    } 
    else 
    { 
        $res .= $int_unit . '整'; 
    } 
    return $res; 
}

function move_file($oldfile,$dir,$newfile)
{
	if(!file_exists($dir)) {
		return mkdir($dir,0777,true);
	}
	
	$result=rename($oldfile,$newfile);
	return $result;
}

function hidden_some_email_str($email)
{
	list($email_name,$email_addr)=explode('@', $email);
	$start=ceil(strlen($email_name)/3);
	$repeat=strlen($email_name)-$start;
	$replace_str=str_repeat('*', $repeat);
	$email_name=substr_replace($email_name, $replace_str, ceil(strlen($email_name)/3));
	return $email_name.'@'.$email_addr;
}
